package com.tgy.myplus.基础学习.Thread.Lock;

import lombok.SneakyThrows;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 送你一块二向箔
 * @date 2021/11/09 11:09
 */
public class TestLock {
    public static void main(String[] args) {
        TestLock1 testLock1 = new TestLock1();
        while (testLock1.tickets>0) {
            new Thread(testLock1,"甲").start();
            new Thread(testLock1,"乙").start();
            new Thread(testLock1,"丁").start();
        }


    }
}

class TestLock1 implements Runnable {
    int tickets = 10;


    //定义lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @SneakyThrows
    @Override
    public void run() {
        //while (true) {
            try {
                lock.lock();//加锁
                if (tickets > 0) {
                    Thread.sleep(20);
                    System.out.println(Thread.currentThread().getName() + tickets--);
                } //else {
                    //break;
                //}
            } catch (Exception e) {
                e.getStackTrace();
            } finally {
                lock.unlock();//解锁
            }
    }
}
